package edu.chl.tda367.mynotes.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;

import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;

/*
 * Class that handles the reading and saving of files.	
 */

public class FileHandler implements IFileHandler {
	
	private String text; 
	private StringBuilder sb = new StringBuilder();
	private RTFEditorKit editorKit = new RTFEditorKit();
	
	private FileHandler(){
		
	}
	public static FileHandler newInstance(){
		return new FileHandler();
	}
	
	
	@Override
	public String loadFile(String fileName) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(fileName));
				String line;
			    while((line = br.readLine()) != null){
			    	sb.append(line);
			    }			    
			    br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			text = sb.toString();
			return text;
		}

	@Override
	public void saveFile(File file, StyledDocument sd) {
		File fChoosen = file;
		try{
			OutputStream out = new FileOutputStream(fChoosen);
			editorKit.write(out, sd, 0,  sd.getLength());
			out.close();
		}
		catch (Exception ex){
			ex.printStackTrace();
		}	
	}
}
